package com.qingyun.quartz.task;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qingyun.quartz.domain.TiktokPushTask;
import com.qingyun.quartz.mapper.TiktokPushTaskMapper;
import com.qingyun.shop.domain.TiktokShop;
import com.qingyun.shop.domain.TiktokShopInfo;
import com.qingyun.shop.mapper.AuthoAppConnectMapper;
import com.qingyun.shop.mapper.TiktokUserShopMapper;
import com.qingyun.shop.service.ITiktokShopInfoService;
import com.qingyun.shop.service.ITiktokShopService;
import com.qingyun.tiktok.basis.response.video.VideoListRes;
import com.qingyun.tiktok.basis.service.interfaces.DyBasisService;
import com.qingyun.tiktok.common.enums.ApiPlatform;
import com.qingyun.tiktok.domain.TiktokVideoSend;
import com.qingyun.tiktok.mapper.TiktokVideoSendMapper;
import me.chanjar.weixin.common.error.WxErrorException;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Classname TiktokTask
 * @Author dyh
 * @Date 2021/9/16 12:09
 */
@Component("tiktokTask")
public class TiktokTask {

	@Autowired
    private TiktokPushTaskMapper pushTaskMapper;
	@Autowired
    private TiktokVideoSendMapper videoSendMapper;
	@Autowired
    private  DyBasisService dyBasisService;
	@Autowired
    private VideoSendService videoSendService;
	@Autowired
    private RedissonClient redissonClient;
	@Autowired
	private WxMaService wxMaService;

	@Autowired
	private ITiktokShopService shopService;

	@Autowired
	private AuthoAppConnectMapper appConnectMapper;

    /**
     * 发送视频
     */
    @Transactional(rollbackFor = Exception.class)
    public void sendVideo() {
        RLock lock = redissonClient.getLock("VIDEO_KEY");
			if (lock.tryLock()) {
				//查询待发布的视频任务
              try {
				  Date date = new Date();
				  LambdaQueryWrapper<TiktokPushTask> lqw = Wrappers.lambdaQuery();
				  lqw.eq(TiktokPushTask::getStatus, 0);//任务执行状态：0待执行，1执行成功 2执行失败
				  lqw.le(TiktokPushTask::getSendTime, date);
				  List<TiktokPushTask> pushTaskList = pushTaskMapper.selectList(lqw);

				  if (pushTaskList == null || pushTaskList.size() < 1) {
					  return;
				  }
				  for (TiktokPushTask pushTask : pushTaskList) {
					  try {
						  videoSendService.mergeVideoSend(pushTask.getActivityId(), pushTask.getUserId(), pushTask.getId());
					  } catch (Exception ignored) {
						  ignored.printStackTrace();
						  pushTask.setStatus(2);
						  pushTaskMapper.updateById(pushTask);
					  }
				  }
			  }finally {
				  lock.unlock();
			  }
			}

    }

	/**
	 * 发送订阅消息
	 */
	public void sendMsg(){
		List<TiktokShop> list = shopService.lambdaQuery().le(TiktokShop::getVideoCount, 100).le(TiktokShop::getRemindCount,3).ne(TiktokShop::getIsProxy,1).list();
		list.forEach((shop)-> {
			shop.setRemindCount(shop.getRemindCount()+1);
			shopService.updateById(shop);
			//提醒商家
				List<String> users = appConnectMapper.selectOpenIdByShopId(shop.getId());
				users.forEach(openId->{
					WxMaSubscribeMessage wxMaSubscribeMessage = new WxMaSubscribeMessage();
					wxMaSubscribeMessage.setToUser(openId);
					wxMaSubscribeMessage.setTemplateId("QsHEAFFjrarLXA2nId3aJyBYoWQqZC7ECYU7rMlIyX0");
					WxMaSubscribeMessage.MsgData msgData1 = new WxMaSubscribeMessage.MsgData();
					msgData1.setName("amount1");
					msgData1.setValue(shop.getVideoCount()+"次");
					wxMaSubscribeMessage.addData(msgData1);
					WxMaSubscribeMessage.MsgData msgData2 = new WxMaSubscribeMessage.MsgData();
					msgData2.setName("phrase2");
					msgData2.setValue("商户");
					wxMaSubscribeMessage.addData(msgData2);
					WxMaSubscribeMessage.MsgData msgData3 = new WxMaSubscribeMessage.MsgData();
					msgData3.setName("thing3");
					msgData3.setValue(shop.getName());
					wxMaSubscribeMessage.addData(msgData3);
					WxMaSubscribeMessage.MsgData msgData4 = new WxMaSubscribeMessage.MsgData();
					msgData4.setName("thing4");
					msgData4.setValue("您的转发余额已不足"+shop.getVideoCount()+"次，请及时充值，以免影响顾客使用。");
					wxMaSubscribeMessage.addData(msgData4);
					wxMaSubscribeMessage.setPage("pages/combo/index");
					try {
						wxMaService.getSubscribeService().sendSubscribeMsg(wxMaSubscribeMessage);
					} catch (WxErrorException e) {
						e.printStackTrace();
					}
				});
			    //提醒代理商
				if (shop.getProxyId().equals(-1L)) {
					return;
				}
		        TiktokShop proxyShop = shopService.lambdaQuery().eq(TiktokShop::getProxyId, shop.getProxyId()).eq(TiktokShop::getIsProxy, 1).one();
				if (ObjectUtil.isNull(proxyShop)) {
					return;
				}
				List<String> proxyUsers = appConnectMapper.selectOpenIdByShopId(proxyShop.getId());
				proxyUsers.forEach((openId)->{
					WxMaSubscribeMessage wxMaSubscribeMessage = new WxMaSubscribeMessage();
					wxMaSubscribeMessage.setToUser(openId);
					wxMaSubscribeMessage.setTemplateId("QsHEAFFjrarLXA2nId3aJyBYoWQqZC7ECYU7rMlIyX0");
					WxMaSubscribeMessage.MsgData proxymsgData1 = new WxMaSubscribeMessage.MsgData();
					proxymsgData1.setName("amount1");
					proxymsgData1.setValue(shop.getVideoCount()+"次");
					wxMaSubscribeMessage.addData(proxymsgData1);
					WxMaSubscribeMessage.MsgData proxymsgData2 = new WxMaSubscribeMessage.MsgData();
					proxymsgData2.setName("phrase2");
					proxymsgData2.setValue("你的商户");
					wxMaSubscribeMessage.addData(proxymsgData2);
					WxMaSubscribeMessage.MsgData proxymsgData3 = new WxMaSubscribeMessage.MsgData();
					proxymsgData3.setName("thing3");
					proxymsgData3.setValue(shop.getName());
					wxMaSubscribeMessage.addData(proxymsgData3);
					WxMaSubscribeMessage.MsgData proxymsgData4 = new WxMaSubscribeMessage.MsgData();
					proxymsgData4.setName("thing4");
					proxymsgData4.setValue("您的商家："+shop.getName()+"转发余额已不足"+shop.getVideoCount()+"次，请联系商家进行充值。");
					wxMaSubscribeMessage.addData(proxymsgData4);
					try {
						wxMaService.getSubscribeService().sendSubscribeMsg(wxMaSubscribeMessage);
					} catch (WxErrorException e) {
						e.printStackTrace();
					}
				});

	     }
		);
	}


    /**
     * 定时更新已发布的抖音视频的点赞评论播放数据
     */
    @Transactional(rollbackFor = Exception.class)
    public void dyVideoDataTask() {
        LambdaQueryWrapper<TiktokVideoSend> lqw = Wrappers.lambdaQuery();
        lqw.eq(TiktokVideoSend::getStatus, 1);
        //一个视频只抓取5次
        lqw.lt(TiktokVideoSend::getIteration, 5L);
        List<TiktokVideoSend> videoSendList = videoSendMapper.selectList(lqw);
        if (videoSendList == null || videoSendList.size() < 1) {
            return;
        }
        for (TiktokVideoSend tiktokVideoSend : videoSendList) {
            String itemId = tiktokVideoSend.getItemId();
            String openId = tiktokVideoSend.getOpenId();
            String[] videoIds = {itemId};
            VideoListRes.VideoListResData data = dyBasisService.getVideoService().getVideoData(openId, videoIds, ApiPlatform.DOU_YIN);
            List<VideoListRes.VideoDetail> details = data.getList();
            if (details == null || details.size() < 1) {
                continue;
            }
            VideoListRes.VideoStatistics statistics = details.get(0).getStatistics();
            if (statistics == null) {
				continue;
            }
            tiktokVideoSend.setDiggCount((long) statistics.getDiggCount());
            tiktokVideoSend.setDownloadCount((long) statistics.getDownloadCount());
            tiktokVideoSend.setForwardCount((long) statistics.getForwardCount());
            tiktokVideoSend.setPlayCount((long) statistics.getPlayCount());
            tiktokVideoSend.setShareCount((long) statistics.getShareCount());
            tiktokVideoSend.setCommentCount((long) statistics.getCommentCount());
            // 抓取次数加1
            tiktokVideoSend.setIteration(tiktokVideoSend.getIteration() + 1L);
            videoSendMapper.updateById(tiktokVideoSend);
        }
    }
}

